<template>
  <el-main>
    <div class="mt-4">
      <el-row>
        <el-col :span="12">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item>
              <el-select v-model="formInline.ifpay" placeholder="请选择状态" clearable>
                <el-option value="已支付" />
                <el-option value="未支付" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getorderbyifpay">
                <el-icon><Search /></el-icon>筛选
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8"></el-col>
      </el-row>
    </div>
    <el-row>
      <el-table :data="tableData" class="table" border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="time" label="创建时间" width="180">
          <template #default="scope">
            <span>{{ scope.row.addtime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="water" label="用水量" width="100">
          <template #default="scope">
            <span>{{ scope.row.usedWater }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="water_price" label="水费" width="100">
          <template #default="scope">
            <span>{{ scope.row.waSum }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="electrical" label="用电量" width="100">
          <template #default="scope">
            <span>{{ scope.row.usedElc }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="electrical_price" label="电费" width="100">
          <template #default="scope">
            <span>{{ scope.row.elSum }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="账单金额" width="100">
          <template #default="scope">
            <span>{{ scope.row.sum }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="pay_status" label="是否支付" width="100">
          <template #default="scope">
            <el-tag :class="scope.row.ifpay === '已支付' ? 'success-pay' : 'danger-pay'">
              {{ scope.row.ifpay }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pay_time" label="截止日期" width="180">
          <template #default="scope">
            <span>{{ scope.row.endLine }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              :disabled="scope.row.ifpay === '已支付'"
              :class="{ 'disabled-button': scope.row.ifpay === '已支付' }"
            >
              支付
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <br />
    <el-config-provider :locale="locale">
      <el-pagination
        style="margin-left: 50%"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
      />
    </el-config-provider>
  </el-main>
  <div id="receipt" v-html="receiptContent" style="display: none"></div>
</template>
<script lang="ts" setup>
import { ref, reactive } from "vue";
import { computed } from "vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import en from "element-plus/dist/locale/en.mjs";
import { onMounted } from "vue";
import axios from "axios";

const form = reactive({
  name: "",
  address: "",
  telephone: "",
});

const select = ref("");
const handleClick = () => {
  console.log("click");
};
const Search = ref("");
const language = ref("zh-cn");
const locale = computed(() => (language.value === "zh-cn" ? zhCn : en));
const toggle = () => {
  language.value = language.value === "zh-cn" ? "en" : "zh-cn";
};

const dialogVisible = ref(false);

const pageSize = ref(6); // 每页显示10条数据
const currentPage = ref(1);
const total = ref(0); // 总记录数

const tableData = ref<Orders[]>([]);
const receiptData = reactive({
  ordId: "",
  payTime: "",
  sum: "",
  ifpay: "",
});

const getOrderbyuserid = () => {
  const user = localStorage.getItem("user");
  const user2 = JSON.parse(user);
  const user_id = user2.userId;

  if (!user_id) {
    console.error("用户未登录或 userId 不存在");
    return;
  }
  const params = new URLSearchParams();
  params.append("user_id", user_id);
  axios
    .get(`http://localhost:8080/orderInfo/selectorderbyuserid`, {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        user_id: user2.userId,
      },
    })
    .then((response) => {
      tableData.value = response.data.data.records;
      total.value = response.data.data.total;
    });
};

const getorderbyifpay = () => {
  const ifPay = formInline.ifpay || "";
  const user = localStorage.getItem("user");
  const user2 = JSON.parse(user);
  const user_id = user2.userId;

  const params = new URLSearchParams();
  params.append("user_id", user_id);
  params.append("ifpay", ifPay);

  axios
    .get(`http://localhost:8080/orderInfo/selectorderbyifpay`, {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        ifpay: formInline.ifpay,
        user_id: user2.userId,
      },
    })
    .then((response) => {
      tableData.value = response.data.data.records;
      total.value = response.data.data.total;
    });
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getorderbyifpay();
};

onMounted(() => {
  getOrderbyuserid();
  getorderbyifpay;
});

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
const activeIndex = ref("1");
const activeIndex2 = ref("1");
const handleSelect = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

interface Orders {
  addtime: string;
  ordId: string;
  realname: string;
  place: string;
  phone: string;
  usedWater: string;
  waSum: string;
  usedElc: string;
  elSum: string;
  sum: string;
  ifpay: "未支付" | "已支付";
  endLine: string;
  address: string;
  userId: string;
}

const handleEdit = async (index, row) => {
  if (row.ifpay === "已支付") {
    alert("该订单已支付！");
    return;
  }
  const user = localStorage.getItem("user");
  const user3 = JSON.parse(user);
  const user_id = user3.userId;
  const ord_id = row.ordId;

  const params = new URLSearchParams();
  params.append("user_id", user_id);
  params.append("ord_id", ord_id);
  const confirmPay = window.confirm("您确定要支付吗？");

  if (confirmPay) {
    try {
      const response = await axios.get(`http://localhost:8080/orderInfo/checkBalance`, {
        params: { ord_id: row.ordId, user_id: user3.userId },
      });

      if (response.data.data == true) {
        const updatedOrder = {
          ...row,
          ifpay: "已支付",
        };

        const response = await axios.put(
          `http://localhost:8080/orderInfo/update`,
          updatedOrder
        );

        if (response.data.code === 0) {
          row.ifpay = "已支付";
          getOrderbyuserid();
          console.log("支付状态更新成功");

          // 更新支付凭证数据
          receiptData.ordId = row.ordId;
          receiptData.payTime = new Date().toLocaleString();
          receiptData.sum = row.sum;
          receiptData.ifpay = "已支付";

          // 生成支付凭证并提供下载
          generateReceipt();
        } else {
          console.error("支付状态更新失败:", response.data.message);
          alert("支付状态更新失败，请稍后重试！");
        }
      } else {
        alert("余额不足，请充值！");
      }
    } catch (error) {
      console.error("支付状态更新失败:", error);
      alert("支付状态更新失败，请稍后重试！");
    }
  }
};

const formInline = reactive({
  ifpay: "",
});

const onSubmit = () => {
  console.log("submit!");
};

const generateReceipt = () => {
  const receiptContent = `<div style="display: flex; justify-content: center; align-items: center; flex-direction: column; font-size: 24px;">
    <h1 style="font-size: 36px;">支付凭证</h1>
    <h1>支付金额: <span style="font-size: 48px;">${receiptData.sum}</span> 元</h1>
    <h3>订单编号: ${receiptData.ordId}</h3>
    <h3>支付时间: ${receiptData.payTime}</h3>
    <h3>支付状态: ${receiptData.ifpay}</h3>
    <div><h3>支付方式: 支付宝</h3></div>
    <div><h3>支付对象: 水电先锋电力公司</h3></div>
  </div>`;
  const blob = new Blob([receiptContent], { type: "text/html" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "receipt.html";
  a.click();
  URL.revokeObjectURL(url);
};
</script>

<style>
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.center {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
.tranlate {
  display: none;
}
.table {
  width: 85%;
  margin-left: 50px;
  margin-top: 20px;
}
.success-pay {
  background-color: #67c23a;
  color: white;
}
.danger-pay {
  background-color: #f56c6c;
  color: white;
}
/* .pagination {
  text-align: center;
  margin-top: 20px;
  margin-left: 450px;
} */
.disabled-button {
  cursor: not-allowed;
  opacity: 0.6;
}

</style>
